package com.zxc.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zxc.common.constant.CartConstant;
import com.zxc.common.utils.R;
import com.zxc.common.vo.SkuInfoVo;
import com.zxc.gulimall.cart.feign.ProductFeignService;
import com.zxc.gulimall.cart.interceptor.CartInterceptor;
import com.zxc.gulimall.cart.service.CartService;
import com.zxc.gulimall.cart.vo.Cart;
import com.zxc.gulimall.cart.vo.CartItem;
import com.zxc.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;


    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null){
            Long userId = userInfoTo.getUserId();
            String cartKey = CartConstant.CART_PREFIX +userId;
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().filter(
                    (item) -> item.getCheck()
            ).map((item)->{
                //更新为商品的最新价格
                BigDecimal skuPrice = productFeignService.getSkuPrice(item.getSkuId());
                item.setPrice(skuPrice);
                return item;
            }).collect(Collectors.toList());
            return cartItems;
        }else {
            return null;
        }
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String string = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),string);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        //是登陆还是没有没有登录
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId() != null){
            //1、登录
            String cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserId();//登录用户的购物车key

            //2、如果临时购物车有数据还需要进行合并操作
            List<CartItem> tempCartItems = getCartItems(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
            if (tempCartItems != null){
                //临时购物车有数据，需要合并
                for (CartItem cartItem : tempCartItems){
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                }
            }

            //获取登录后的购物车的数据【包含临时购物车的数据和登录后的购物车的数据】
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

            //清除临时购物车
            clearCart(CartConstant.CART_PREFIX + userInfoTo.getUserKey());
        }else {
            //2、没有登录
            String cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserKey();
            BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(cartKey);
            //获取临时购物车的购物商品项
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String cartStr = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(cartStr,CartItem.class);
        return cartItem;
    }

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = new CartItem();

        String cart = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(cart)){
            //购物车没有此商品
            //异步编排执行任务，线程池
            CompletableFuture<Void> skuInfoTask = CompletableFuture.runAsync(() -> {
                //1、远程查询需要添加的商品的信息
                R skuInfo = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                //2、商品信息data添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setSkuId(data.getSkuId());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setPrice(data.getPrice());
            },executor);

            //3、远程查询sku的组合信息
            CompletableFuture<Void> skuSaleAttrTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);

            //等异步任务先完成了再进往redis放数据
            CompletableFuture.allOf(skuInfoTask,skuSaleAttrTask).get();

            //以商品Id为key进行hash存储 string
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(),s);
        }
        else {
           //购物车有这个商品，我们只需要加上数量即可
            CartItem cartItem1 = JSON.parseObject(cart, CartItem.class);
            Integer count = cartItem1.getCount();
            count = count + num;
            cartItem1.setCount(count);
            String s = JSON.toJSONString(cartItem1);
            cartOps.put(skuId.toString(),s);
            return cartItem1;
        }

        return cartItem;
    }



    //获取我们要操作的购物车
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        //1、判断用临时用户车，还是用户车
        String cartKey = "";
        if (userInfoTo.getUserId() != null){
            //说明登录了，我们使用登录的购物车
            //gulimall:cart:1
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserId();
        }else {
            cartKey = CartConstant.CART_PREFIX+userInfoTo.getUserKey();
        }

        //获取我们购物车的信息
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(cartKey);

        return boundHashOps;
    }

    private List<CartItem> getCartItems(String cartKey){
        BoundHashOperations<String, Object, Object> boundHashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = boundHashOps.values();
        if (values != null && values.size() > 0){
            List<CartItem> collect = values.stream().map((obj) -> {
                String string = (String) obj;
                CartItem cartItem = JSON.parseObject(string, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }
}
